package com.bs.upstream.controller;

import com.bs.utils.XHttpClientUtil;
import com.google.common.collect.Maps;
import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
public class DemoController2 {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoController2.class);

    // NOTE
    //public static final String API_MODEL = "http://10.70.108.55:8888/api-model/request_model.sdo";
    public static final String API_MODEL = "http://127.0.0.1:8888/api-model/request_model.sdo";


    public static final String PROXY_SERVER = "http://192.1.2.3:8888";


    @Value("classpath:" + "response.json")
    private Resource responseResource;

    /**
     * @return api-upstream/request_model.sdo
     */
    @RequestMapping(value = "/api-upstream/request_model2.sdo", method = {RequestMethod.GET, RequestMethod.POST})
    public String request_model(HttpServletRequest request, HttpServletResponse response) {
		//
		String content = "";

		//
		Map<String, String> headers = Maps.newHashMap();
		headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		headers.put("Accept", "text/plain;charset=utf-8");
		List<NameValuePair> list = new ArrayList<>();

		// NOTE
		Map<String, String[]> map = request.getParameterMap();
		Set<Map.Entry<String, String[]>> entries = map.entrySet();
		for (Map.Entry<String, String[]> entry : entries) {
			if (entry.getValue() != null && entry.getValue().length > 0) {
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()[0]));
			}
		}

        try {
            // no proxy
            Map<String, String> r = (Map<String, String>) XHttpClientUtil.sendPost(API_MODEL, headers, list);
            // with proxy
            //Map<String, String> r = (Map<String, String>) XHttpClientUtil.sendPost(Optional.of(PROXY_SERVER), API_MODEL, headers, list);

            LOGGER.info(r.toString());
            // NOTE
            content = r.toString();
        } catch (Exception e) {
            LOGGER.error(e.getLocalizedMessage());

            // NOTE 请求python失败， 则从本地加载一个mock response.json. 集成方可以无视下面几行代码
            try {
                content = IOUtils.toString(this.responseResource.getInputStream(), "UTF-8");
            } catch (Exception e2) {
                content = e2.getLocalizedMessage();
            }

        }


        return content;
    }
}
